'use strict';

/*
* 
*   Route Configuration
*
*/
var shopApp = angular.module('shopApp', ['shopApp.services','ngRoute'])
  .config(['$routeProvider', function($routeProvider) {

    // default route
    $routeProvider.when('/', {templateUrl: 'views/main.html',controller: 'MainCtrl'}).otherwise({redirectTo: '/'});

    // carts route
    $routeProvider.when('/cart',{templateUrl:'views/cart-list.html', controller: 'CartCtrl'});
  }]);




/*
* 
*   Cart Engine
*
*/
shopApp.run(function($rootScope, localStorage,uiConfigResource){
  // init empty storage only for debug
  // localStorage.set('cart',[]);
  // localStorage.set('cart-count',0);
  // get main uiConfig
  $rootScope.uiConfig=uiConfigResource.query();
  // vars
  var cart =  $rootScope.cart = localStorage.get('cart');
  var items = $rootScope.itemsOnCart = localStorage.getN('cart-count');

  // adding item to cart
  $rootScope.addToCart = function(item){
    var itemFound = false;
    if (items>0){
      cart.forEach(function(current){
        if (current.code == item.code){
          current.quantity += 1;
          itemFound=true;
        }
      });
    }

    items += 1;
    if (!itemFound){
      item.quantity = 1;
      item.completed = true;
      cart.push(item);
    }
    localStorage.set('cart', cart);
    localStorage.set('cart-count',items);
    $rootScope.itemsOnCart = items;
  };


  // remove item from cart
  $rootScope.removeItem = function(item){
    if (items<=0){return false;}
    items -=item.quantity;
    cart.splice(cart.indexOf(item),1);
    localStorage.set('cart',cart);
    localStorage.set('cart-count', items);
    $rootScope.itemsOnCart = items;
  };

  // get subtotal
  $rootScope.getSubTotal = function(){
    var subtotal = 0;
    cart.forEach(function(current){
      subtotal += Number(current.price);
    });
    return subtotal;
  };

  // get total
  $rootScope.getGrandTotal =  function(){
    var grandTotal = 0;
    cart.forEach(function(current){
      grandTotal += (Number(current.price) * Number(current.quantity));
    });
    return grandTotal;

  };


  // proceed to checkout
  $rootScope.proceedToCheckout = function(){
    cart = $rootScope.cart = [];
    items = $rootScope.itemsOnCart = 0;

    localStorage.set('cart', cart);
    localStorage.set('cart-count',items);

  };
  

});
